<!-- 教师端统计分析整体模块 -->
 <!-- 注意：1、当没有分的时候，查不到数据（尤其是图表）
          2、取最新数据显示，一个人有多篇论文的话，只会显示最新的 -->
<template>
  <div>
      <div class="year-select">
        <div style="font-size: 17px">毕业年份：</div>
        <el-select v-model="selectedYear" placeholder="请选择学生毕业年份" class="sta-select" @change="updateYearData">
          <el-option
            v-for="item in yearOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>

      <div class="score-table">
        <div class="number">
          <div class="number-title">学生数量</div>
          <div class="number-score">{{ overview.studentTotal }}</div>
        </div>
        <div>
          <div class="number-title">及格人数</div>
          <div class="number-score">{{ overview.passCount }}</div>
        </div>
        <div>
          <div class="number-title">平均总分</div>
          <div class="number-score">{{ overview.averageTotalScore }}</div>
        </div>
        <div>
          <div class="number-title">五个大分平均分</div>
          <div class="number-score">{{ overview.fiveFactorAvgScoreMultiplyCount }}</div>
        </div>
        <div class="number">
          <div class="number-title">最高总分</div>
          <div class="number-score">{{ overview.maxTotalScore }}</div>
        </div>
        <div>
          <div class="number-title">最低总分</div>
          <div class="number-score">{{ overview.minTotalScore }}</div>
        </div>
      </div>

      <div class="all-data">
        <div class="sta-title">全部数据统计</div>
        <div ref="radarChart" class="radar-chart"></div>
        <div class="bar-container">
          <el-select
            v-model="selectedMetric"
            placeholder="请选择评分维度"
            class="select-name"
            @change="updateBarChart"
          >
            <el-option label="总分" value="avgTotalScore" />
            <el-option label="选题意义评分" value="topicSignificance" />
            <el-option label="写作安排评分" value="writingSchedule" />
            <el-option label="逻辑构建评分" value="logicalStructure" />
            <el-option label="专业能力评分" value="professionalAbility" />
            <el-option label="学术规范评分" value="academicNorms" />
          </el-select>
          <div ref="barChart" class="bar-chart"></div>
        </div>
      </div>

      <!-- <div class="student-table-container">
        <el-table :data="filledTableData" border class="student-table">
          <el-table-column prop="name" label="学生姓名" width="120" fixed/>
          <el-table-column prop="avgTotal" label="平均总评分"/>
          <el-table-column prop="maxTotal" label="最高总评分"/>
          <el-table-column prop="minTotal" label="最低总评分"/>
          <el-table-column prop="workload" label="工作量评分"/>
          <el-table-column prop="content" label="内容组织评分"/>
          <el-table-column prop="research" label="文献调研评分"/>
          <el-table-column prop="logicScore" label="逻辑结构评分"/>
          <template #empty>
            <div v-for="i in emptyRowCount" :key="i" class="empty-row"></div>
          </template>
        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="studentList.length"
          class="pagination"
          :pager-count="5"
        />
      </div> -->
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios'
import {
  getAllYearsByTeacher,
  getAllPaperByTeacher,
  getTeacherHomeOverview
} from "@/api/teacher.js";


const yearOptions = ref([]);
const selectedYear = ref('');
const yearData = ref({})
const userId = localStorage.getItem('userId')

//概览
const overview = ref({
  studentTotal: 0,
  passCount: 0,
  averageTotalScore: 0,
  fiveFactorAvgScoreMultiplyCount: 0,
  maxTotalScore: 0,
  minTotalScore: 0
})


// 年份选项
// const yearOptions = [
//   { value: '2025', label: '2025' },
//   { value: '2024', label: '2024' },
//   { value: '2023', label: '2023' },
//   { value: '2022', label: '2022' },
//   { value: '2021', label: '2021' },
// ];


//下拉框
const getyear = async () =>{
  try{
    
    console.log(userId)
    const res = await getAllYearsByTeacher(userId) // 作为入参
    console.log(res.data)
    yearOptions.value = res.data.map(y => ({
      label: y,
      value: y
    }));
    if (res.data.length > 0) {
      selectedYear.value = res.data[0]; // 默认选中第一个
    }
    
    updateYearData(); // 拿到年份后更新图表

  }catch(error){
    ElMessage.error('统计分析年份获取失败')
  }
}
// 拉取某一年的数据
const updateYearData = async () => {
  if (!selectedYear.value) return;
  try {
    const viewdata = await getTeacherHomeOverview(userId,selectedYear.value)
    overview.value = viewdata.data
    console.log("概述：",viewdata.data)
    const table = await getAllPaperByTeacher(userId, selectedYear.value);
    yearData.value[selectedYear.value] = table.data; // 存成 { year: [students] }
    console.log(table.data)
    updateRadarChart();
    updateBarChart();
  } catch (error) {
    ElMessage.error('获取学生成绩失败');
  }
};

// 学生数据处理
const studentList = computed(() => {
  const rawStudents = yearData.value[selectedYear.value] || [];
  return rawStudents.map(student => ({
    name: student.studentName,
    avgTotalScore: student.totalScore || 0,
    topicSignificance: student.firstScore || 0,
    writingSchedule: student.secondScore || 0,
    logicalStructure: student.thirdScore || 0,
    professionalAbility: student.fourthScore || 0,
    academicNorms: student.fifthScore || 0
  }));
});
const selectedMetric = ref('avgTotalScore');


// 图表容器
const radarChart = ref(null);
const barChart = ref(null);
let radarInstance = null;
let barInstance = null;

// 初始化雷达图
const initRadarChart = () => {
  radarInstance = echarts.init(radarChart.value);
  updateRadarChart();
};

// 更新雷达图
const updateRadarChart = () => {
  const students = studentList.value;
  if (!students.length) {
    radarInstance?.clear();
    return;
  }

  const indicator = [
    { name: '总分', max: 100 },
    { name: '选题意义', max: 100 },
    { name: '写作安排', max: 100 },
    { name: '逻辑构建', max: 100 },
    { name: '专业能力', max: 100 },
    { name: '学术规范', max: 100 }
  ];

  const studentSeries = students.map(student => ({
    name: student.name,
    value: [
      student.avgTotalScore,
      student.topicSignificance,
      student.writingSchedule,
      student.logicalStructure,
      student.professionalAbility,
      student.academicNorms
    ],
    lineStyle: { width: 1 },
    symbolSize: 4
  }));
  console.log("雷达图数据", studentSeries);


  const option = {
    tooltip: {
      trigger: 'item',
      formatter: params => {
        const labels = ['总分', '选题意义', '写作安排', '逻辑构建', '专业能力', '学术规范'];
        return params.value.map((v, i) => `${labels[i]}: ${v}`).join('<br/>');
      }
    },
    legend: {
      data: studentSeries.map(s => s.name),
      type: 'scroll',
      bottom: 0
    },
    radar: {
      indicator,
      radius: '65%',
      splitNumber: 4
    },
    series: [{
      type: 'radar',
      data: studentSeries
    }]
  };

  radarInstance.setOption(option);
};

// 初始化柱状图
const initBarChart = () => {
  barInstance = echarts.init(barChart.value);
  updateBarChart();
};

// 更新柱状图
const updateBarChart = () => {
  const metricMap = {
    avgTotalScore: '总分',
    topicSignificance: '选题意义',
    writingSchedule: '写作安排',
    logicalStructure: '逻辑构建',
    professionalAbility: '专业能力',
    academicNorms: '学术规范'
  };

  const students = studentList.value;
  if (!students.length) {
    barInstance?.clear();
    return;
  }

  const xData = students.map(s => s.name);
  const yData = students.map(s => s[selectedMetric.value]);

  const option = {
    title: {
      text: `学生${metricMap[selectedMetric.value]}对比`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}: {c}分'
    },
    xAxis: { type: 'category', data: xData },
    yAxis: { type: 'value', min: 0, max: 100, name: '分数' },
    series: [{
      type: 'bar',
      data: yData,
      label: { show: true, position: 'top' }
    }]
  };

  barInstance.setOption(option);
};


// 自适应
const handleResize = () => {
  radarInstance?.resize();
  barInstance?.resize();
};

onMounted(() => {
  getyear();
  initRadarChart();
  initBarChart();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  radarInstance?.dispose();
  barInstance?.dispose();
});
</script>


<style scoped>
.year-select {
  display: flex;
  align-items: center;
  margin: 20px 0;
  gap: 10px;
}

.sta-select {
  width: 200px;
}

.score-table {
  margin: 20px 0;
  background-color: #f8f8f8;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: row;
  gap: 150px;
  justify-content: center;
  text-align: center;
  
}

.score {
  width: 100%;
  margin-bottom: 15px;
}

.all-data {
  background-color: #f8f8f8;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.radar-chart {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.bar-container {
  margin: 30px 0;
  background-color: #f8f8f8;
  padding: 20px;
  border-radius: 4px;
}

.bar-chart {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}

.select-name {
  width: 200px;
  margin-bottom: 15px;
}

.student-table-container {
  margin-top: 20px;
  margin-right: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
  width: 100%;
}

.student-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.score :deep(.el-table__header th),
.student-table :deep(.el-table__header th) {
  text-align: center;
  background-color: #f0f0f0;
  font-weight: bold;
  user-select: none;
}

.score :deep(.el-table__body td),
.student-table :deep(.el-table__body td) {
  text-align: center;
  height: 50px;
}
.sta-title{
  font-size: 20px;
}

.number-title{
  margin: 10px;
}
.number-score{
  margin: 20px 0;
}
</style>